<?php
/**
 * Created by PhpStorm.
 * User: denh
 * Date: 16/5/17
 * Time: 下午2:13
 */
require_once ROOT_PATH . "tools/tools.page.php";
require_once ROOT_PATH . "tools/tools.tongji.php";
require_once ROOT_PATH . 'bs/BsUserCenter.php';
require_once ROOT_PATH . 'bs/BsStatistics.php';

class BaseController extends Base {

    Const SECRET_KEY = '95e6de86ef6e4f36b65440739ef5e654'; #接口秘钥

    public $m = '';
    public $a = '';
    public $template = '';
    public $Js = '';     #js url路径
    public $JsFile = ''; #js磁盘路径
    public $initJs = '';
    public $tongjiUrl = '';
    public $signPackage = array();
    public static $hproseHttpClient = null;
    public $关注引导页 = "http://mp.weixin.qq.com/s?__biz=MzI3NjE2OTU3NA==&mid=403902577&idx=1&sn=153a3ede424f16e8586dc33d5b3fab8a&scene=0&previewkey=eApt5HNBZqOZzDiMbGw5F8wqSljwj2bfCUaCyDofEow%3D#wechat_redirect";

    function __construct($m = DEFAULT_CONTROLLER, $a = DEFAULT_METHOD) {
        parent::__construct();
        $this->m = $m;
        $this->a = $a;
        $this->template = ROOT_PATH . 'app/templates/' . $m . '/' . $a .'.html';
        $this->JsFile   = ROOT_PATH . 'app/js/' . $m . '/' . $a .'.js';
        $this->Js       = G_SITE_BASE . '/app/js/' . $m . '/' . $a .'.js';

        $this->tongjiUrl = _cnzzTrackPageView(1259747134);
        if (is_file($this->template)) {
            $this->load_jssdk();
        }
        $logRequest =  Logger::getInstance2();
        $logRequest->log_path = G_LOG_PATH . '/request';
        $logRequest->logInfo("===REQUEST_URI===:".$_SERVER['REQUEST_URI'].
            "\n openid:".$this->openId().
            "\n POST:".var_export($_POST, true).
            "\n"
        );

        logger()->logInfo("===BaseController: openid: ". $this->openId(). "session_id:". session_id());
    }

    function __destruct() {
        if (is_file($this->JsFile)) {
            echo "\n".'<script language="JavaScript">' . "\n";
            require_once $this->JsFile;
            echo "\n" . '</script>';
        }
        #上报当日活跃用户
        if ($this->openId()) {
            $statistics = new \bs\BsStatistics();
            $statistics->activeUser($this->openId());
        }
    }

    function template($m = '', $a = '') {
        if (!$m) $m = $this->m;
        if (!$a) $a = $this->a;
        return ROOT_PATH . 'app/templates/' . $m . '/' . $a . '.html';
    }

    function load_jssdk($url = '') {
        require_once ROOT_PATH . 'business/jssdk.php';
        $数据 = pdo()->selectColumns('public_serv_accounts',array('AppSecret','app_id'),array('id' => G_SERV_ID));
        $jssdk = new JSSDK($数据['app_id'], $数据['AppSecret']);
        $this->signPackage = $jssdk->getSignPackage($url);
    }

    function load_hprose($base_url = BACK_INTERFACE_BASE_URL) {
        require_once ROOT_PATH . 'sdk/hprose-php-master/src/Hprose.php';
        self::$hproseHttpClient = new \HproseHttpClient($base_url);
    }

    #获取openid后跳回到当前页面
    function redirectToWeixinForOpenid() {
        #$source = $this->request('source', 'weixin');
        if (!$this->isLogin()) {
            require_once ROOT_PATH . 'app/controller/WxLoginController.php';
            $get = $_GET;
            unset($get['m']);
            unset($get['a']);
            $url = WxLoginController::wxGzhUrl($this->m, $this->a, $get);
            logger()->logInfo("WxUrl:".$url);
            header("Location:" . $url);
        }
    }

    function isLogin() {
        if (isset($_SESSION['vo用户数据']['公众号ID']) && $_SESSION['vo用户数据']['公众号ID'] != G_SERV_ID) {
            session_destroy();
            return false;
        }
        if (!isset($_SESSION['userCenter']['id']) or !$_SESSION['userCenter']['id']) {
            return false;
        }
        if (isset($_SESSION['vo用户数据']['openID']) and !empty($_SESSION['vo用户数据']['openID'])) {
            return true;
        }

        return false;
    }

    function get_UserCenterToken($openId) {
        if (empty($_SESSION['userCenter']['token'])) {
            $bsUserCenter = new BsUserCenter();
            $bsUserCenter->getInfoFromUserCenter($openId);
        }
        return $_SESSION['userCenter']['token'];
    }

    function must_subscribe() {
        $doUser = new Do用户();
        $doUser->set_openID($_SESSION['vo用户数据']['openID']);
        $doUser->set_unsubscribe(0);
        if (!$doUser->where($doUser->data)->count()) {
            $alert =  sprintf("<script>alert('请先关注爱贝儿医'); location.replace('%s');</script>", $this->$关注引导页);
            exit($alert);
        }
    }

    function isSubscribe() {
        wzd()->init微信接口($this->openId(), '', C信息中心::get实列根据用户Oid($this->openId()));
        $vsInfo = wzd()->vc公众号->f获取用户基本信息();
        logger()->logInfo("isSubscribe获取用户微信信息：". var_export($vsInfo, true));
        if ($vsInfo) {
            $vo用户信息 = json_decode($vsInfo);
            if ($vo用户信息->subscribe == 1) {
                return true;
            }
            return false;
        }
        return false;
    }

    /**
     * @return string
     */
    function openId(){
       // return "oKkVJxLy0CvhDpGy5VLHpCbAoaQY";
      return $_SESSION['vo用户数据']['openID'];
    }

    function url($m, $a, $param = array()) {
        $url = G_SITE_BASE . "/index.php?m=$m&a=$a";
        if ($param) {
            $q = http_build_query($param);
            $url = $url.'&'.$q;
        }
        return $url;
    }

    function url_linhe($page, $param = array()) {
        $state = array();
        $state[] = $page;
        $state['publicnumber'] = G_SERV_ID;
        $state = array_merge($state, $param);
        $state = "000" . urlencode(json_encode($state));
        $url = sprintf("%s/business/index.php?state=%s", G_SITE_BASE, $state);
        return $url;
    }

    function redirect($m, $a, $param = array()) {
        $url = $this->url($m, $a, $param);
        header("Location:".$url);
    }

    function request($str, $default = '', $isMust = false) {
        if (!array_key_exists($str, $_REQUEST) and $isMust) {
            $str = sprintf("%s 为必填字段", $str);
            if (is_file($this->template)) {
                $this->errorPage($str);
            } else {
                $this->jsonOutPut(-1, $str);
            }
        }
        $value = array_key_exists($str, $_REQUEST) ? $_REQUEST[$str] : $default;
        return trim($value);
    }

    function jsonOutPut($status, $msg='', $data=array()) {
        $result = new \BoOutPuts($status, $msg, $data);
        exit(json_encode($result));
    }

    function initScript($data = array()) {
        $data = json_encode($data);

        $initJs = "<script language='javascript'>
        function get_init_data(){return %s}\n</script>\n";

        $this->initJs = sprintf($initJs, $data);
    }

    function errorPage($Msg, $jumpUrl = '') {
        require ROOT_PATH . 'app/templates/common/errorPage.html';
        exit();
    }

    function successPage($Msg, $jumpUrl = '') {
        require ROOT_PATH . 'app/templates/common/successPage.html';
        exit();
    }

    function get_js() {
        if (is_file($this->JsFile)) {
            echo sprintf("<script src= '%s' language='JavaScript'></script>", $this->Js);
        }
    }

    #获取app接口token
    function tourist_login() {
        if (G_SERV_ID == 14) {
            $_SESSION['app_token'] = '0cf452fb28fb474b9ced6eedfb1dadfd8a7b85edf76b4cbc9125d5bf8c2b1cd4';
        } else {
            $_SESSION['app_token'] = 'fd45e92edbb641548a9c2d036bc8e66c4756acfa05544515b8aff6a8b4f02e52';
        }
    }

    function preg_img_cdn($str) {
        $str = preg_replace('/<img[^>]*? src="\/([^"|^>|:]*)"[^>]*?\/>/',
            '<img src="http://static.tianshiyumiao.com/$1"/>', $str);
        return $str;
    }

}

class BoOutPuts
{
    public $result = -1;
    public $datas = '';
    public $message = '错误';

    public function __construct($result = -1, $message = '', $datas = '')
    {
        $this->datas = $datas;
        $this->message = $message;
        $this->result = $result;
    }
}
